import React, { useEffect, useState } from 'react'
import ProForm, { ProFormText } from '@ant-design/pro-form'
import Editor from '@/components/Editor'
import { editWebConfig, getWebConfigDetail } from '@/services/webconfig'
import { Card, message } from 'antd'
import ProSkeleton from '@ant-design/pro-skeleton'

const UserAgreement = () => {
  // 把获取到的数据存到状态
  const [configer, setConfiger] = useState(null)
  //定义Form实例 用来操作表单
  const [formObj] = ProForm.useForm()

  useEffect(async () => {
    //获取网站配置详情
    const configer = await getWebConfigDetail('user_agreement').then(res => {
      return setConfiger(res.value)
    })

  }, [])

  /**
   * 修改网站配置
   * @param values 表单中输入的数据
   * @returns {Promise<void>}
   */
  const updataWebConfig = async values => {
    /**
     * 定义要修改的字段
     * @type {{cn_name: string, value: {title, confidentiality_agreement}}}
     */
    const data = {
      'cn_name': '用户注册保密协议',
      'value': {
        'title': values.title,
        'confidentiality_agreement': values.confidentiality_agreement
      }
    }
    /**
     * 执行修改
     * @type {*}
     */
    const response = await editWebConfig('user_agreement', data)
    if (response.status === undefined) {
      message.success('修改成功')
    }
  }

  /**
   * 文件上传成功后设置文件上传的value
   * @param fileKey
   * @returns {*}
   */
  const setDetails = content => {
    formObj.setFieldsValue({ 'confidentiality_agreement': content })
  }

  return (
    <div>
      {
        configer == null ?
          <div
            style={{
              background: '#fafafa',
              padding: 24,
            }}
          >
            <ProSkeleton type="list"/>
          </div> :
          <Card>
            <ProForm
              form={formObj}
              onFinish={values => updataWebConfig(values)}
              initialValues={configer}
              submitter={{
                // 配置按钮的属性
                resetButtonProps: {
                  style: {
                    // 隐藏重置按钮
                    display: 'none',
                  },
                },
              }
              }
            >
              <ProFormText
                name="title"
                label="用户注册保密协议标题"
                colon={true}
                tooltip="最长为 24 位"
                placeholder="请输入标题"
                rules={[{ required: true, message: '请输入保密协议标题' }]}
              />
              <ProForm.Item
                name="confidentiality_agreement"
                label="用户注册保密协议内容"
                rules={[{ required: true, message: '请输入保密协议内容' }]}
              >
                <div>
                  <Editor setDetails={setDetails} content={configer.confidentiality_agreement}/>
                </div>
              </ProForm.Item>
            </ProForm>
          </Card>

      }

    </div>
  )
}

export default UserAgreement
